<template>
  <div class="detail-btn flex-row">
    <div class="btn like" @click="toggleLike">
      <div class="image-wrapper flex-center">
        <img :src="likeSrc" class="image">
      </div>
      <span class="title">{{isLike ? "取消" : "喜欢"}}</span>
    </div>
    <button class="btn share" open-type="share" plain>
      <div class="image-wrapper flex-center">
        <img src="/static/btn-icon/share.svg" class="image">
      </div>
      <span class="title">分享</span>
    </button>
  </div>
</template>

<script>
const db = wx.cloud.database()
export default {
  name: 'DetailBtn',
  data () {
    return {
      isLike: false
    }
  },
  props: {
    data: {
      type: Object
    }
  },
  computed: {
    likeSrc () {
      return this.isLike ? '/static/btn-icon/heart_full.svg' : '/static/btn-icon/heart.svg'
    }
  },
  methods: {
    async toggleLike () {
      this.isLike = !this.isLike
      if (this.isLike) {
        await db.collection('likes')
          .add({
            data: {
              ...this.data,
              createTime: db.serverDate()
            }
          })
      } else {
        wx.cloud.callFunction({
          name: 'removeLike',
          data: {
            _id: this.data._id
          }
        })
          .then(res => {
            console.log(res)
          })
      }
    },
    _checkIsLike () {
      db.collection('likes').where({_id: this.data._id})
        .limit(1)
        .get()
        .then(res => {
          if (res.data.length === 1) {
            this.isLike = true
          }
        })
    }
  },
  mounted () {
    this.isLike = false
    this._checkIsLike()
  },
  onShow () {
    this.isLike = false
    this._checkIsLike()
  }
}
</script>

<style lang="stylus" scoped>
  .detail-btn
    width 100%
    justify-content space-around
    .btn
      display flex
      flex-direction column
      align-items center
      justify-content space-around
      &.share
        padding 0
        margin 0
        border none
        .image-wrapper
          background-color #00ff80
      &.like
        .image-wrapper
          background-color #FD5B78
      .image-wrapper
        width 40px
        height 40px
        border-radius 50%
        .image
          width 20px
          height 20px
      .title
        line-height 20px
        font-size 12px
        color #999
</style>
